﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace memcached.Tx
{
    /// <summary>
    /// We assume null is not a valid value.
    /// </summary>
    internal class SetOp : KeyedOp
    {
        [System.Diagnostics.DebuggerHidden]
        public SetOp(ICache real, ICache temp, string key, object value)
            : base(real, temp, key)
        {
            Value = value;
        }

        protected readonly object Value;
        protected object Original;
        protected bool Done;

        public override string Name
        {
            [System.Diagnostics.DebuggerHidden]
            get { return "Set:" + Key; }
        }

        public override object Execute()
        {
            // TODO another solution is to use real store and lock the key for other transactions
            return Temp.Set(Key, Value);
        }

        public override bool Persist()
        {
            // we assume failure means it was not updated,
            // but if anthing fails we need to restore the state in Rollback
            bool res;
            Original = Store.Get(Key, out res);// we assume null is not a valid value
            if (res)
                res = Store.Set(Key, Value);
            Done = res;
            return res;
        }

        public override bool Rollback()
        {
            if (Done && Original != null)
                return Store.Set(Key, Original);// we loose expiry information here
            return true;// if it was not set, than nothing to reset
        }
    }
}
